package com.cn.wanxi.util;//package com.cn.wanxi.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {//init 启动时执行

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Access-Control-Allow-Origin","http://localhost:8082");//后台跨域问题
        resp.setHeader("Access-Control-Allow-Credentials","true");
        String url=req.getServletPath();//到访问路径
//url.endsWith("/a/")以a结尾
//url.startsWith("/b/" )以b开始
        if (url.startsWith("/back/" ) || url.startsWith("/producat/")){
            String username= (String) req.getSession().getAttribute("username");//得到session
            if (username == null){
                resp.getWriter().println(400);
            }else {
                filterChain.doFilter(req,resp);//放行操作
            }
        }else {
            filterChain.doFilter(req,resp);//放行操作
        }
    }

    @Override
    public void destroy() {//结束时运行

    }
}
